/*
 * Created on 12/08/2005
 *
 */
package gurulab.merlin.core.router;

import gurulab.maya.common.PhoneAddress;
import gurulab.maya.common.RelativeApplicationAddress;
import gurulab.merlin.core.RuleSyntaxErrorException;
import gurulab.merlin.core.envelope.Envelope;
import bsh.EvalError;
import bsh.Interpreter;
import bsh.NameSpace;


/**
 * El interpretador de reglas se basa en el interpretador Beanshell (http://www.beanshell.org/) limitando
 * unicamente que los resultados de la regla sea un valor booleano.
 *
 * No se ha verificado huecos de seguridad. Dado que es de uso interno no se considera peligroso.
 * @author Cesar Obach-Renner, cesar AT gurulab.org
 * @version 2.0
 * @see http://www.beanshell.org/
 */
public class RuleEvaluator {
    Interpreter interpreter;

    /**
     * @author Cesar Obach-Renner, cesar AT gurulab.org
     */        
    public RuleEvaluator (){
        NameSpace ns;
        interpreter = new Interpreter ();
        ns=interpreter.getNameSpace ();
        ns.importPackage ("gurulab.maya.common");
        interpreter.setNameSpace (ns);
    }
    
    /**
     * @param rule
     * @param envelope
     * @return boolean
     * @throws gurulab.merlin.core.RuleSyntaxErrorException
     * @author Cesar Obach-Renner, cesar AT gurulab.org
     */    
    public boolean evaluate (String rule, Envelope envelope) throws RuleSyntaxErrorException{
        try {
            interpreter.set ("envelope", envelope);
            Object o=interpreter.eval (rule);
            
            if (o.getClass ()!=Boolean.class){
                throw new RuleSyntaxErrorException("Not a boolean result: "+o.toString ());
            }            
            return((Boolean)o).booleanValue ();            
        } catch (EvalError e) {
            throw new RuleSyntaxErrorException ("Detail: "+e);
        }
        
    }
    
    public static void main (String[] argv) throws Exception{
        RuleEvaluator re=new RuleEvaluator ();        
        Envelope env=new Envelope ("Esta es una prueba", new PhoneAddress ("58","412","6210713"), new RelativeApplicationAddress ("digitel","CANAL"));        
        String rule="envelope.getDestination().getClass()==gurulab.maya.common.PhoneAddress";        
        try{
            System.out.println ("==>"+re.evaluate (rule, env));
        } catch(RuleSyntaxErrorException e){
            System.err.println ("Exception ocurred: "+e);
        }
    }
        
    
}